// Após a inicialização do documento.
$(function() {

	$(".produto-lancamento").each(function(){
		$(this).text("Lançamento");
	});
	
    //$('.bread-crumb li a:contains("Daslu")').html("Store");

	if ( $('body.resultado-busca').size() > 0 )	{
        
        $('.resultado-busca #category-navigation h3:has(a)').each(function() {
            $(this).html( $(this).find('a').html() );
        });
    
	}
	
    $('#navigation li').find('li:last:not(li li li)').addClass('notchild');
    
	$("#departament-rightbar .main .vitrine .prateleira").find("ul").each(function(){
		var originalText = $(this).find("li a span.produto-nome").text();

		if(originalText.length > 30){
			var shortText = originalText.substr(0, 30);
			if(shortText.charAt(30) != " "){
				shortText = shortText.substr(0, shortText.lastIndexOf(" "));
			}
			$(this).find("li a span.produto-nome").text(shortText + " ...");
		}
	});
	
    // Substituindo as fontes do menu por cuffons.
	Cufon.replace('#navigation a:not("ul ul ul a")', {
        fontFamily: 'Proxima Nova Rg',
        hover: { color: '#fff' } 
    });
	
	Cufon.replace('.cufon', {
        fontFamily: 'Proxima Nova Rg'
    });
	
    // Substituindo as fontes do menu inferior por cuffons.
    Cufon.replace('#footer-navigation ul li a', {
        fontFamily: 'Proxima Nova Rg',
        hover: { color: '#fff' } 
    });

	// Substituindo as fontes da página de produtos por cuffons.
    Cufon.replace('#heading .bread-crumb ul li, #heading h1', {
        fontFamily: 'Proxima Nova Rg'
    });
    Cufon.replace('.produto h1', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#product .about h2', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#product .about .share', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#product .about .share', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#indications h3', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#look .about-look ul li .look-information .name', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#look-header-box h1', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('.prateleira li a', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('.giftList-wrapper span.name', {
        fontFamily: 'Proxima Nova Rg'
    });
	
	// Departamentos
	Cufon.replace('#departament-navigation h4', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#departament-navigation h4 a', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#departament-navigation h5', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#departament-navigation h5 a', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#departament-rightbar .prateleira li a span', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#lookwrapper .items .item .name', {
        fontFamily: 'Proxima Nova Rg'
    });

	// Categorias
	Cufon.replace('#categorycontent .prateleira li a span', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('#category-navigation h5', {
        fontFamily: 'Proxima Nova Rg'
    });
	
	
	// Legado
	Cufon.replace('body .content h2', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('body.login .content h4', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('body.login .sign-in label', {
        fontFamily: 'Proxima Nova Rg'
    });
	
	//carrinho
	Cufon.replace('table.carrinhoTable thead th, table.carrinhoTable thead td', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('.endereco .lista-endereco legend span', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('body.carrinho .carrinho-vazio h3, body.checkout .cadastro-endereco h3', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('body.minha-conta #orderInfoProductList th', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('.breadcrumb ul li, .bread-crumb ul li', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('.descricao-compra thead th', {
        fontFamily: 'Proxima Nova Rg'
    });
	
	// Daslu Indica

	Cufon.replace('.hotsite-productswrapper ul li a:not(:has(.hotsite-name))', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('.hotsite-sellerindication ul li a', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('.sellerfield .hotsite-seller-name', {
        fontFamily: 'Proxima Nova Rg'
    });
	Cufon.replace('.collection-about .collection-name', {
        fontFamily: 'Knockout'
    });
	
	Cufon.replace('#usewith li a span, #otherlooks li a span, #mostview li a span, #daslulove li a span, #lastviews li a span', {
		fontFamily: 'Proxima Nova Rg'
	});
	
	Cufon.replace('.listas .address h2, .listas .giftlist-table tr th', {
		fontFamily: 'Proxima Nova Rg'
	});

	$(".listas div.giftlist").next().css("display", "none");
	$(".listas ul.giftlist-action").insertAfter("table.giftlist-table").css("margin", "0").find("li").css({"float": "right", "margin-right": "0"});
	$('#navigation li:not(li li):has(ul)').addClass('arrowDown');
	$("table.giftlist-table #btnReferAFriend").html("Indique a lista para até quatro amigos");
	$("table.giftlist-table").find("tr td").each(function(){
		if($(this).attr("class").indexOf("giftlist-body-action") != -1){
			
			$(this).find("a").wrapInner("<span class='tooltip' />");
			$(this).find("a").append("<span class='tooltip-arrow' />");
			
			var width = (($(this).find("span.tooltip").outerWidth())/2) * (-1);
			$(this).find("span.tooltip").css("margin-left", width);
			
			
			if($(this).attr("class") == "giftlist-body-action"){ $(this).find("a").append("<img src='/Control/ArquivoExibir.aspx?NomeArquivo=alterar.png' alt='' />"); }
			if($(this).attr("class") == "giftlist-body-action-sendfriend"){ $(this).find("a").append("<img src='/Control/ArquivoExibir.aspx?NomeArquivo=amigo.png' alt='' />"); 
                
            }
			if($(this).attr("class") == "giftlist-body-action-gerenciar"){ $(this).find("a").append("<img src='/Control/ArquivoExibir.aspx?NomeArquivo=gerenciar.png' alt='' />"); }
			if($(this).attr("class") == "giftlist-body-action-visualizar"){ $(this).find("a").append("<img src='/Control/ArquivoExibir.aspx?NomeArquivo=visualizar.png' alt='' />"); }
		}
	});
    
    $('.giftlist-header-name').html("Nome da lista");
    
	$('.giftlist-body-action').remove();
	$('.giftlist-body-codigo').remove();
	$('.giftlist-body-eventdate').remove();
	$('.giftlist-body-finaly').remove();
	$('.giftlist-header-codigo').remove();
	$('.giftlist-header-eventdate').remove();
	$('.giftlist-header-finaly').remove();
	$('.giftlist-header-action').attr({'colspan': 3 });
    
    // Slider do Background da Index.
    $('#background #background-slider').DasluSlider( { 'enableKeyboard' :  true } );
	// Slider das Thumbs dos produtos.
    $('#product ul.thumbs').DasluProductSlider( {  } );
    
	if($.browser.msie && $.browser.version=="6.0") {
	
		// Fixing the layout height bug
		$(window).resize(function() {

			if( $('#general').height() < $(window).height() ) {  
			
				$('#general').height( $(window).height() );
				$('#background').height( $('#general').height() );
				$('#header,#main,#footer').show();
			
			}else {
				$('#background').height( $('#general').height() );
				$('#header,#navigation,,#main,#footer').show();
			}
		});
		
		if( $('#general').height() < $(window).height() ) {  
			
			$('#general').height( $(window).height() );
			$('#background').height( $('#general').height() );
			$('#header,#main,#footer').show();
		
		}else {
			$('#background').height( $('#general').height() );
			$('#header,#navigation,,#main,#footer').show();
		}
		
	
	}
	
    $("#indica-wrap #slider-content").offset();
	
	// Criando a UI de seleção de tamanho
    $('#product #espec_0_opcao_0').jQSelect({ rotulo : "Selecione uma op&ccedil;&atilde;o", selectfirst : false });
	
	$('.main .sub .resultado-busca-filtro .orderBy select option:contains(Mais Vendidos)').remove();
	$('.main .sub .resultado-busca-filtro .orderBy select option:contains(Mais bem Avaliados)').remove();
	$('.main .sub .resultado-busca-filtro .orderBy select option:contains(Data de)').remove();
	$('.main .sub .resultado-busca-filtro .orderBy select option:contains(A - Z)').remove();
	$('.main .sub .resultado-busca-filtro .orderBy select option:contains(Z - A)').remove();
	// Criando a UI para seleção da ordenação
	$(".main .sub .resultado-busca-filtro .orderBy select").eq(0).jQSelect();
	Cufon.replace('#category-navigation .refino .ver-filtros', {
		fontFamily: 'Proxima Nova Rg'
	});
	
	// Tratando layout do restultado de buscas
	
	if($(".didyoumean").length > 0){
		$(".didyoumean:eq(1)").remove();
		$("#category-control").insertAfter(".didyoumean");
		$("#category-control").css({"margin": "11px 0"});
		$("#category-control").find("li").css({"height": "auto", "width": "auto"});
		$("#category-control").find("li a").css({"height": "auto", "width": "auto"});
		
		var tmp = $(".didyoumean").children().remove();
		$(".didyoumean").text("Você quis dizer: ").append(tmp).html($(".didyoumean").html() + " ?");
		
		Cufon.replace('.didyoumean', {
			fontFamily: 'Proxima Nova Rg'
		});
	}
	
    if($(".busca-vazio").length > 0){
		$("#category-control").insertAfter(".busca-vazio");
		$("#category-control").css({"margin": "11px 0"});
		$("#category-control").find("li").css({"height": "auto", "width": "auto"});
		$("#category-control").find("li a").css({"height": "auto", "width": "auto"});
		
		
		Cufon.replace('.busca-vazio', {
			fontFamily: 'Proxima Nova Rg'
		});
	}
    
	//$('#look .about-look ul li .thumbnail').hover(function () {
		
		//#look #printimage .apresentacao #show
		//var offset = $('#look #printimage .apresentacao #show').offset();
		//$(".jqZoomWindow").offset({ top: offset.top, left: offset.left });
		
	
	//});
	
	// Eventos da Interface
	$('#navigation li').mouseenter(function (){
		$(this).find('ul:first').show();
	});
	$('#navigation li').mouseleave(function (){
		$(this).find('ul').hide();
	});
	
	$('.prateleira li').live('mouseenter',function() {
		$(this).find('span:not(.soldmini)').show();
	});
	$('.prateleira li').live('mouseleave', function() {
		$(this).find('span:not(.soldmini)').hide();
	});
	
	$('#usewith li, #otherlooks li, #mostview li, #daslulove li, #lastviews li').live('mouseenter',function() {
		$(this).find('span:not(.soldmini)').stop().fadeTo('fast',1);
	});
	$('#usewith li, #otherlooks li, #mostview li, #daslulove li, #lastviews li').live('mouseleave', function() {
		$(this).find('span:not(.soldmini)').stop().fadeTo('fast',0);
	});
	
	
	$('.item').find('a').each(function() {
		$(this).attr("href" , "/quick-view/?idproduto=" + $(this).attr("rel") + "?KeepThis=true&TB_iframe=true&width=220&height=210");
	});
	
	$('.item .anchor').click(function () {
		$(this).parent().find('a').trigger('click');
	});
	
	$('.item a').click(function(e) {
		
		//e.preventDefault();
		
	});
	
	$('#lookwrapper .controls .buy .buybutton').click(function(e) {
		
		//e.preventDefault();
		
	});
	
	
	// When The anchor has hovered.
	$('item').mouseenter(function() {
		$(this).find('.name').fadeIn('fast');
	});
	//When The Item anchor has leaved.
	$('item').mouseleave(function() {
		$(this).find('.name').delay(300).hide();
	});
	
	// When The buy button has hovered.
	$('.buy').mouseenter(function() {
		$(this).find('.information').fadeIn('fast');
	});
	//When The Item buy button has leaved.
	$('.buy').mouseleave(function() {
		$(this).find('.information').delay(300).hide();
	});
	
	
	
	
	
	

	// Removendo os li's que não possuirem look's desnecessarios
	$('#look .about-look #look-list li .name:empty').each(function() {
	
		$(this).parent().parent().remove();
	
	});
	//$('#look .about-look #look-list li:not(:has(input))').remove();
	
	// Aplicando o slider vertical no google.
	$('#look-list').VerticalSlide({},11);
		
	
	$(".searchWrapper:first").appendTo("#searchbar");
	Cufon.replace('#searchbar', {
        fontFamily: 'Proxima Nova Rg'
    });
		// Link de retorno para o login
	if($("#cart").find("p.loginmsg").length > 0){
		var originalURL = $("#cart p.loginmsg a").attr("href");
		originalURL = originalURL + "?ReturnUrl=" + encodeURI(location.pathname) + encodeURI(location.search);
		$("#cart p.loginmsg a").attr("href", originalURL);
	}
	
	// Link de retorno para o logout
	// Isso não funciona por causa do BACK-END!!!
	
	var logoutReturnLink = setTimeout(function(){
		if($("#lnkLogOut").length > 0){
			var originalURL = $("#lnkLogOut").attr("href");
			originalURL = originalURL + "?ReturnUrl=" + encodeURI(location.pathname) + encodeURI(location.search);
			$("#lnkLogOut").attr("href", originalURL);
		}
	}, 2000);
	
	$(document).ajaxComplete(function(event,request, settings){
	
		$("#cart .giftlisttypecountitems").html( '(' + $("#cart .giftlisttypecountitems").html().replace("(","").replace(")","").replace(" ","").replace("\n","") + ')' );

		if ( $('.amount-items a').size() == 0 ) {
		
			$('.amount-items').append('<a href="/cart/"> </a>');
		
		}
	
		
		if ( $(".cartInfoWrapper .amount-items-em").size() > 0 ) {
	
		var qtd = $(".cartInfoWrapper .amount-items-em").html();
		var qtd = qtd.replace("(","");
		var qtd = qtd.replace(")","");
		var qtd = qtd.replace(" ","");
		//var cartItens = $(".carrinho-cheio").text().match(/\d+/gi);
		//if(cartItens != null) qtd = cartItens;

		
		$(".cartInfoWrapper .amount-items-em").empty().html("(" + qtd + ")");
		//$(".cartInfoWrapper .amount-items-em").text( $(".cartInfoWrapper .amount-items-em").text().replace(/\d+/,"(" + qtd + ")") );
		
		$('.amount-items').find('.amount-items-em').appendTo('.amount-items a');
		
		}
		
		$(".loginmsg").prependTo("#cart");
		
		//substitui o texto "clique aqui" por "Não é você?" no header
		var cliqueAqui = $("#pnlNaoSeguro em a").clone();
		var position = $(".wishlishbutton").offset();
		$("#pnlNaoSeguro em").text("");
		$("#pnlNaoSeguro em").append(cliqueAqui);
		$("#pnlNaoSeguro em a").text( $("#pnlNaoSeguro em a").text().replace("clique aqui","Não é Você?") );
		
		if( $("#cart .loginmsg a:contains('Login')").size() > 0 ){
			
			offsettext = $('#cart .loginmsg').offset();
			offseticon = $('#cart .cartInfoWrapper .amount-items .amount-items-em').offset();
			if(offseticon != null){
				$('#cart .loginmsg').offset({ left: offseticon.left });
			}
				
		}
		
		//$("#pnlNaoSeguro").offset({top:36, left:position.left-91});
		
		//substitui o texto "Ja é Cadastrado, clique aqui" por "Login" no header
		var loginmsg = $(".loginmsg em a").clone();
		$(".loginmsg em").text("");
		$(".loginmsg em").append(loginmsg);
		$(".loginmsg em a").text( $(".loginmsg em a").text().replace("clique aqui","Login") );
		
		
	});

	/*$('.share a').mouseenter(function () {
	
		$(this).stop().fadeTo("fast", 0.4);
	
	}); 
	
	$('.share a').mouseleave(function () {
	
		$(this).stop().fadeTo("fast", 1);
	
	}); */
	
	

	// Manipulando os elementos DOM
	$(".main .sub .resultado-busca-filtro .orderBy .jQcustomselect").prependTo("#category-control");
	/*$('#category-navigation .refino label').click(function () {
	
		$('#category-navigation .bt-refinar').trigger('click');
		
	});*/
	
	
	/*
	$('.st_facebook_large, .st_twitter_large').bind('click', function(e) {
    
        e.preventDefault();
        
        $('.st_email_large').trigger('click');
        return false;
        
    });

    
	$('.st_facebook_large, .st_twitter_large').live('click', function(e) {
    e.preventDefault();
        
        $('.st_email_large').trigger('click');
        return false;
        
    });
    
    */
    
	/* ESCONDE TOTAL DE PRODUTOS POR CATEGORIA */
	if ( $('body').is('.departamento')) {
		
		$('#departament-navigation ul li a, #departament-navigation h4, #leftside .refino label, #leftside #category-navigation .search-single-navigator ul:first').each(function () {
			var oldString = $(this).html();
			var newString = oldString.replace(/\([0-9]+\)/, "");
			$(this).html(newString);
		});
	}
	
	if ( $('body').is('.categoria')) {
		

		
		//$('.search-single-navigator').hide();
		$('.search-multiple-navigator').show();
		
		scriptsSource = $('script:contains(#ResultItems)').html();
		regexFuction = /buscapagina(.+)PageNumber=/;
		url = regexFuction.exec(scriptsSource);
       
		pagination = 2;		
		havePages =  true;
		
		$(window).scroll(function(){
		
			if  ($(window).scrollTop() == $(document).height() - $(window).height() ){
			
                if ($.browser.msie) {
                    getProducts(url,pagination);
                }else{
                    getProducts(url[0],pagination);
                }
				
				pagination++;

			}
			
		}); 
	
	}

    // Funcoes da Wishlish gerencia
    
    if ( $('body').is('.listas') ) {
		
		if($(".loginmsg").length > 0){
			window.location = location.protocol + "//" + location.hostname + '/Site/Login.aspx?ReturnUrl=/lista/gerenciar';
		}else{
	
			$('#openmodal').html("Criar nova lista").attr({'href' : '#TB_inline?height=100&width=410&inlineId=' + $('#openmodal').attr('href') + '&modal=true' });
			$('.giftlist-action-create').empty();
			$('#openmodal').appendTo('.giftlist-action-create');
			$('#openmodal').show();
			
			$('.giftlist-action').appendTo("#main");
			
			// Selecionando o tipo wish lish
			$('#giftlisttype').val( $('#giftlisttype option:contains("Wishlist")').val());
			
			$('#giftlistname').keyup(function() {
			
				$('#giftlistgifeted, #giftlistmessage').val( $(this).val() );
			
			});
			
			$("#TB_closeWindowButton").live('click', function(){
				$("#TB_overlay").trigger("click");
			});
			
			// Data
			$('#giftlisteventdate').val('31/12/2050');
			
			// url
			$('#giftlisturl').val( randomString() )
			$('.listas .address fieldset ul.address-list-select input:first').removeAttr('disabled').click();
			
			$(document).ajaxComplete(function(event,request, settings){
				var waittoajax = setTimeout( function() {
					Cufon.replace('#div-title, #legYourData, #legFriendsData, #fldMessage', {
						fontFamily: 'Proxima Nova Rg' 
					});
				},1500);
			});
		}
    }
    
    var deviceAgent = navigator.userAgent.toLowerCase();
	var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
	if (agentID) {
 
        if( $(window).height() < $('#general').height() ){
           
            $('#footer').css({ 'position' : 'static' });
        
        }
	}
    
});
	
$(document).ready(function () {
    
    
	var delayfix = setTimeout(menufix,1500);

	var loginLink = setTimeout(function(){$('#lblLoginMsg').wrap("<a href='/Vitrine/minhaconta/minhaconta.aspx' />")}, 2000);
	
	var loginLink = setTimeout(function(){
		if($(".loginmsg").length == 1){
			$("#product #likeitbox #resenha #rtAvaliacao_Star_5").css({
				"background": "url('/Control/ArquivoExibir.aspx?NomeArquivo=img_loveit_login_hover.png') no-repeat scroll 0 0 transparent",
				"left": "50%",
				"margin-left": "-70px",
				"top": "-60px",
				"width": "140px"
			});
			$("#product #likeitbox #resenha #rtAvaliacao_A").attr({onmouseout: "", href: "/Site/Login.aspx"});
		}
	}, 2000);
    
    
    var printheader = setTimeout(function(){

        $('#header .wrapper').fadeTo(500, 1);
          
	}, 1600);
    
    
    var googleAnalyticsTrackers = setTimeout(function(){
	
		/* 
		*	INÍCIO DO CÓDIGO DE SOCIAL TAG - FBIZ
		*	************NÃO APAGUE***************
		*/
		setTimeout(function(){var a=document.createElement("script");
		var b=document.getElementsByTagName('script')[0];
		a.src=document.location.protocol+"//dnn506yrbagrg.cloudfront.net/pages/scripts/0010/4256.js";
		a.async=true;a.type="text/javascript";b.parentNode.insertBefore(a,b)}, 1);
		/* TÉRMINO DO CÓDIGO DE SOCIAL TAG - FBIZ */
	
		$(".share").each(function(){
			$(this).find("li").each(function(){
			
				var link = $(this).find(" > span").attr("class");
				var url = location.pathname;
				var network = '';
				var action = '';
				
				if(link == "st_facebook_large"){
					network = 'facebook';
					action = 'share';
				}
				if(link == "st_twitter_large"){
					network = 'twitter';
					action = 'share';
				}
				if(link == "st_email_large"){
					network = 'email';
					action = 'send';
				}
				$(this).bind("click", function(){
					_gaq.push(['_trackSocial', network, action, url]); 
				});
			});
		});
	}, 3000);

	
});	


function menufix() { //

	//Corrigindo o espacamento do menu
	var size = 0;
	$('#navigation li:not(li li)').delay(500).each(function () {
		size += ( $(this).width() + 8 );
	});

	var diference = ( parseInt( $('#navigation').width() - size ) / 2 ) ;
	$('#navigation').width( ( $('#navigation').width() - diference ) );
	$('#navigation').css({ 'padding-left' : diference + 'px'  });

}
	
	// Function resposável por carregar os objetos.
	function getProducts (urlajax,start){
		$('#contentloader').show();
		$.post("/" + urlajax + start,    
		function(data){
			if (data != "") {
				$("#main .vitrine .prateleira:last").after(data); 
				Cufon.replace('#main .vitrine .prateleira a', {
					fontFamily: 'Proxima Nova Rg'
				});
			}
			$('#contentloader').hide();
			if (data == "") {
				return false;
			}
		});
	} 
		
function randomString() {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 10;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}